Leetcode198.+算法期中1005. 动态规划问题之最大最小和问题

Leetcode198. House Robber

题目

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

解题分析

这道题别看前面铺垫了一堆东西,其实就是让我们在一个数组中找到一些数,使得这些数之和最大,其中这些数两两不能相邻。那么这道题我们应该怎么来思考呢?

我们不妨可以这样想。假设数组长度为n,要想选出来的数字之和最大并且两两不能相邻,很明显选n/2个数至多(n/2+1)个数出来的和是最大的;比如[1000,80,700,5000,10000],当选出1000、700和10000这三个数时,结果是最大的。那么我们现在来考虑如何选数的问题。

我们都知道,每个数无非就两种情况,要么被选,要么没有被选。而实际上,这道题可以看成是求选了最后一个数之和与没有选最后一个数之和的最大值。所以我们可以尝试用两个数组select和no_select来分别存储选中当前元素的最大和与没有选中当前元素的最大和。
这样的话,初始化情况下:select[0]=nums[0],no_select[0]=0。在遍历数组的过程中,注意到要考虑选中的数两两不能相邻,所以有两种情况如下:
(1)如果不选当前元素nums[i],那么在这种情况下,上一个元素nums[i-1]可选可不选,取决于二者的最大值,即no_selcet[i]=max(select[i-1],no_select[i-1])。
例如:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值